package com.tentative.competition.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReUtil;
import com.tentative.competition.common.constant.CacheConstants;
import com.tentative.competition.common.constant.Constants;
import com.tentative.competition.common.constant.ErrorConstants;
import com.tentative.competition.common.constant.UserConstants;
import com.tentative.competition.common.core.domain.entity.SysRole;
import com.tentative.competition.common.core.domain.entity.SysUser;
import com.tentative.competition.common.core.domain.model.LoginUser;
import com.tentative.competition.common.core.redis.RedisCache;
import com.tentative.competition.common.enums.UserStatus;
import com.tentative.competition.common.exception.ServiceException;
import com.tentative.competition.common.exception.user.*;
import com.tentative.competition.common.model.schedule.param.LoginParam;
import com.tentative.competition.common.utils.DateUtils;
import com.tentative.competition.common.utils.MessageUtils;
import com.tentative.competition.common.utils.SecurityUtils;
import com.tentative.competition.common.utils.StringUtils;
import com.tentative.competition.common.utils.ip.IpUtils;
import com.tentative.competition.framework.manager.AsyncManager;
import com.tentative.competition.framework.manager.factory.AsyncFactory;
import com.tentative.competition.framework.security.context.AuthenticationContextHolder;
import com.tentative.competition.system.mapper.SysRoleMapper;
import com.tentative.competition.system.service.ISysConfigService;
import com.tentative.competition.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 *
 * @author llh
 */
@Component
@Slf4j
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRoleMapper roleMapper;


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    private void checkRole(Long userId, String roleKey){
        List<SysRole> roles = roleMapper.selectRolePermissionByUserId(userId);
        List<String> roleKeys = roles.stream().map(m->m.getRoleKey()).collect(Collectors.toList());
        List<Boolean> isPasss = new ArrayList<>();
        for (String key : roleKeys) {
            if(key.contains(roleKey)){
                isPasss.add(true);
            }else{
                isPasss.add(false);
            }
        }
        if(!isPasss.contains(true)){
            throw new LoginRoleException();
        }
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public void editPassword(LoginParam param){
        SysUser sysUser = null;
        //邮箱
        if (!verifyEmail(param.getEmail())){
            throw new RuntimeException("邮箱格式不正确！");
        }
        sysUser = userService.selectUserByUserName(param.getUsername());
        if (ObjUtil.isEmpty(sysUser)){
            throw new RuntimeException("当前用户不存在！");
        }
        //邮箱验证码的key
        String codeKey = param.getEmail() + "_forget_code";
        String code = stringRedisTemplate.opsForValue().get(codeKey);
        //查询当前邮箱验证码在redis是否存在
        if (!stringRedisTemplate.hasKey(codeKey)){
            throw new RuntimeException("验证码不正确或者已过时！");
        }else if (!code.equals(param.getCode())){
            throw new RuntimeException("验证码不正确！");
        }
        //密码规则校验
        // if (!passWordPattern(param.getPassword())){
        //     throw new RuntimeException("密码规则不符，需包含数字，字母，字符，且长度在5-20位之间！");
        // }
        if(!StringUtils.validate(param.getPassword())){
            throw new ServiceException("密码的长度至少8位，包含大小写、数字和特殊字符");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(param.getPassword()));
        userService.resetPwd(sysUser);
        // 更新缓存用户权限
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
        {
            loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
            tokenService.setLoginUser(loginUser);
        }
    }

    private Boolean verifyEmail(String email){
        String emailMatcher="[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+";
        return Pattern.matches(emailMatcher,email);
    }

    boolean passWordPattern(String passWord){
        String pattern = "^(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{5,20}$";
        return ReUtil.isMatch(pattern, passWord);
    }
}
